<template>
  <div class="game-management">
    <el-card class="management-card">
      <template #header>
        <div class="card-header">
          <div>
            <h1>游戏库管理</h1>
            <p>管理游戏库数据</p>
          </div>
          <div class="header-actions">
            <el-button type="primary" @click="openGameModal">
              <el-icon><Plus /></el-icon>
              添加新游戏
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索游戏名称、描述或问题..."
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 数据为空提示 -->
      <div v-if="!loading && filteredGames.length === 0" class="empty-tip">
        <el-empty description="暂无游戏数据" />
      </div>

      <!-- 游戏表格 -->
      <el-table
        v-else
        v-loading="loading"
        :data="filteredGames"
        style="width: 100%"
        stripe
        row-key="id"
      >
        <el-table-column prop="ID" label="ID" width="80" />
        <el-table-column prop="name" label="名称" width="150" show-overflow-tooltip />
        <el-table-column prop="desc" label="简述" width="200" show-overflow-tooltip />
        <el-table-column prop="problem_to_solve" label="针对问题" width="200" show-overflow-tooltip />
        <el-table-column prop="introduction" label="玩法介绍" width="200" show-overflow-tooltip />
        <el-table-column prop="theory_explanation" label="心理学解释" width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="170" fixed="right" >
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              link
              @click="editGame(row)"
            >
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click="confirmDelete(row)"
            >
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 游戏模态框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑游戏' : '添加新游戏'"
        width="60%"
        @close="resetForm"
      >
        <el-form
          ref="gameFormRef"
          :model="gameForm"   
          :rules="gameRules"
          label-width="120px"
          @submit.prevent
        >
          <el-form-item label="名称" prop="name">
            <el-input v-model="gameForm.name" placeholder="请输入游戏名称" maxlength="50" show-word-limit />
          </el-form-item>
          <el-form-item label="描述" prop="desc">
            <el-input v-model="gameForm.desc" placeholder="请输入游戏描述" maxlength="200" show-word-limit />
          </el-form-item>
          <el-form-item label="针对问题" prop="problem_to_solve">
            <el-input v-model="gameForm.problem_to_solve" placeholder="请输入针对的问题" maxlength="200" show-word-limit />
          </el-form-item>
          <el-form-item label="玩法介绍" prop="introduction">
            <el-input
              v-model="gameForm.introduction"
              type="textarea"
              :rows="4"
              placeholder="请输入游戏玩法介绍"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="理论解释" prop="theory_explanation">
            <el-input
              v-model="gameForm.theory_explanation"
              type="textarea"
              :rows="4"
              placeholder="请输入心理学理论解释"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveGame" :loading="saving">
              {{ isEdit ? '更新' : '创建' }}
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 删除确认对话框 -->
      <el-dialog
        v-model="deleteDialogVisible"
        title="⚠️ 确认删除"
        width="30%"
        align-center
      >
        <p>确定要删除 <strong>{{ gameToDelete?.name }}</strong> 吗？</p>
        <p class="delete-tip">此操作不可撤销，将永久删除该游戏数据。</p>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="deleteDialogVisible = false">取消</el-button>
            <el-button type="danger" @click="deleteGame" :loading="deleting">
              删除
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Edit, Delete, Search } from '@element-plus/icons-vue'
import api from '@/api'

// ========== 响应式状态 ==========
const loading = ref(false)
const saving = ref(false)
const deleting = ref(false)
const dialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const isEdit = ref(false)
const searchQuery = ref('')
const games = ref([])
const gameFormRef = ref(null)
const currentGameId = ref(null)
const gameToDelete = ref(null) // 用于显示删除确认中的游戏名

// ========== 表单数据 ==========
const gameForm = reactive({
    id:'',
  name: '',
  desc: '',
  problem_to_solve: '',
  introduction: '',
  theory_explanation: ''
})

// ========== 表单验证规则 ==========
const gameRules = {
  name: [
    { required: true, message: '请输入游戏名称', trigger: 'blur' },
    { max: 50, message: '名称不能超过50个字符', trigger: 'blur' }
  ],
  desc: [
    { required: true, message: '请输入游戏描述', trigger: 'blur' },
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ],
  problem_to_solve: [
    { required: true, message: '请输入针对问题', trigger: 'blur' },
    { max: 200, message: '问题描述不能超过200个字符', trigger: 'blur' }
  ]
}

// ========== 计算属性 ==========
const filteredGames = computed(() => {
  if (!searchQuery.value.trim()) return games.value
  const query = searchQuery.value.toLowerCase().trim()
  return games.value.filter(game =>
    game.name?.toLowerCase().includes(query) ||
    game.desc?.toLowerCase().includes(query) ||
    game.problem_to_solve?.toLowerCase().includes(query)
  )
})

// ========== 工具方法 ==========
const resetForm = () => {
  if (gameFormRef.value) gameFormRef.value.resetFields()
  Object.assign(gameForm, {
id:'',
    name: '',
    desc: '',
    problem_to_solve: '',
    introduction: '',
    theory_explanation: ''
  })
  currentGameId.value = null
  isEdit.value = false
}

// ========== API 方法 ==========
const loadGames = async () => {
  loading.value = true
  try {
    const data = await api.getGamesList() // 假设拦截器已处理，直接返回 data 数组
    games.value = Array.isArray(data) ? data : []
  } catch (error) {
    ElMessage.error('加载失败：' + (error.message || '请稍后重试'))
    games.value = []
  } finally {
    loading.value = false
  }
}

const openGameModal = () => {
  resetForm()
  dialogVisible.value = true
}

const editGame = (game) => {
  if (!game) return
  isEdit.value = true
  currentGameId.value = game.ID
  Object.assign(gameForm, {
    id : String(game.ID) || '',
    name: game.name || '',
    desc: game.desc || '',
    problem_to_solve: game.problem_to_solve || '',
    introduction: game.introduction || '',
    theory_explanation: game.theory_explanation || ''
  })
  dialogVisible.value = true
}

const saveGame = async () => {
  if (!gameFormRef.value) return

  await gameFormRef.value.validate(async (valid) => {
    if (!valid) return

    saving.value = true
    try {
      const payload = {
        ...gameForm,
      }

      if (isEdit.value) {
        await api.updateGame(payload)
        ElMessage.success('✅ 游戏更新成功')
      } else {
        await api.createGame(payload)
        ElMessage.success('✅ 游戏创建成功')
      }

      dialogVisible.value = false
      await loadGames()
    } catch (error) {
      ElMessage.error('❌ 保存失败：' + (error.message || '未知错误'))
    } finally {
      saving.value = false
    }
  })
}

const confirmDelete = (game) => {
  if (!game) return
  gameToDelete.value = game
  deleteDialogVisible.value = true
}

const deleteGame = async () => {
  if (!gameToDelete.value?.ID) return

  deleting.value = true
  try {
    await api.deleteGame({ id: String(gameToDelete.value.ID) })
    ElMessage.success('✅ 删除成功')
    deleteDialogVisible.value = false
    gameToDelete.value = null
    await loadGames()
  } catch (error) {
    ElMessage.error('❌ 删除失败：' + (error.message || '未知错误'))
  } finally {
    deleting.value = false
  }
}

const handleSearch = () => {
  // 由 computed 自动响应，无需额外逻辑
}

// ========== 生命周期 ==========
onMounted(() => {
  loadGames()
})
</script>

<style scoped>
.game-management {
  padding: 20px;
}

.management-card {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.card-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.card-header p {
  margin: 4px 0 0;
  color: #909399;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-bar {
  margin: 20px 0;
}

.empty-tip {
  margin: 40px 0;
  text-align: center;
}

.delete-tip {
  color: #f56c6c;
  font-size: 14px;
  margin-top: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-table .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

:deep(.el-button.is-link) {
  padding: 0;
  min-width: auto;
}
</style>